import {Component, EventEmitter, Input, OnInit, Output, forwardRef} from '@angular/core';
import {HttpService} from '@kylin/http';
import {DropdownDataService} from '@dropdown';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

export const EXE_COUNTER_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => InvolvedProjectComponent),
    multi: true
};

@Component({
    selector: 'kylin-involved-project',
    templateUrl: './involved-project.component.html',
    styleUrls: ['./involved-project.component.less'],
    providers: [EXE_COUNTER_VALUE_ACCESSOR]
})
export class InvolvedProjectComponent implements OnInit, ControlValueAccessor {
    projects = [];
    _selectedProjects: any[];
    selectedObj = [];
    set selectedProjects(val) {
        this._selectedProjects = val;

        const tmpSelected = [];
        val.map(item => {
            this.projects.map(project => {
                if (item === project.value) {
                    tmpSelected.push(project);
                }
            });
        });
        this.selectedObj = tmpSelected;

        this.propagateChange(val);
    }

    get selectedProjects() {
        return this._selectedProjects;
    }
    @Input() klStyle: { [key: string]: any };
    @Input() klClass: { [key: string]: any };
    isOpen = false;

    propagateChange = (_: any) => {
    };

    constructor(private http: HttpService, private dataSvc: DropdownDataService) {

    }

    ngOnInit() {
        this.dataSvc.getData({name: 'grassItems', cache: true}).then(rst => {
            this.projects = rst;
        });
    }

    toggleSelector(event) {
        event.stopPropagation();
        this.isOpen = !this.isOpen;
    }

    writeValue(value: any) {
        this.selectedProjects = value || [];
    }

    registerOnChange(fn: any) {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any) {

    }
}
